#pragma once

#include <iostream>
#include <string>
#include <stdarg.h>
#include <time.h>

#define LOG "log.txt"
#define LOG_ERR "logerr.txt"

#define DEBUG   0
#define NORMAL  1
#define WARNING 2
#define ERROR   3
#define FATAL   4

#define NUM 1024

const char* to_levelstr(int level)
{
    switch (level)
    {
    case DEBUG: return "DEBUG";
    case NORMAL: return "NORMAL";
    case WARNING: return "WARNING";
    case ERROR: return "ERROR";
    case FATAL: return "FATAL";
    default: return nullptr;
    }
}

void logMessage(int level, const char* format, ...)
{
    //[日志等级] [时间] [pid] [错误信息]
    char logheader[NUM];
    snprintf(logheader, sizeof(logheader), "[%s] [%ld] [pid: %d]",to_levelstr(level), time(nullptr), getpid());

    char logcontent[NUM];
    va_list arg;
    //定位第一个可变参数
    va_start(arg, format);

    vsnprintf(logcontent, sizeof(logcontent), format, arg);

    // std::cout << logheader << logcontent << std::endl;

    //将日志打印至文件
    FILE* log = fopen(LOG, "a");
    FILE* err = fopen(LOG_ERR, "a");
    if(log != nullptr && err != nullptr)
    {
        FILE* cur = nullptr;
        if(level == NORMAL || level == DEBUG || level == WARNING) cur = log;
        else if(level == ERROR || level == FATAL) cur = err;
        fprintf(cur, "%s%s\n", logheader, logcontent);

        fclose(log);
        fclose(err);
    }


    va_end(arg);
    
}